package com.shen.langchain4j.controller;

import cn.hutool.core.date.DateUtil;
import com.shen.langchain4j.entity.ComputerPrompt;
import com.shen.langchain4j.service.ComputerChatAssistant;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/chatPrompt")
public class ChatPromptController {
    @Autowired
    @Qualifier("computerChatAssistant")
    private ComputerChatAssistant computerChatAssistant;

    @Autowired
    @Qualifier("qwen")
    private ChatModel qwen;

    /**
     * 方式一：@SystemMessage+@UserMessage+@V
     *
     * @return 大模型返回结果
     */
    @GetMapping(value = "/chatMethod1")
    public String chatMethod1() {
        String answer1 = computerChatAssistant.chat("计算机由什么组成", 1000);
        log.info("answer1: {}", answer1);
        String answer2 = computerChatAssistant.chat("苹果富含哪些营养", 1000);
        log.info("answer2: {}", answer2);
        return "success :" + DateUtil.now() + "<br> \n\n answer1: " + answer1 + "<br> \n\n answer2: " + answer2;
    }

    /**
     * 方式二：@SystemMessage + 带有@StructuredPrompt的业务实体类
     *
     * @return
     */
    @GetMapping(value = "/chatMethod2")
    public String chatMethod2() {
        ComputerPrompt computerPrompt = new ComputerPrompt();
        computerPrompt.setLanguage("Java");
        computerPrompt.setQuestion("数据基本类型有哪些");
        String answer = computerChatAssistant.chat(computerPrompt);
        log.info("answer: {}", answer);
        return "success :" + DateUtil.now() + "<br> \n\n answer: " + answer;
    }

    /**
     * 方式三： PromptTemplate+Prompt
     *
     * @return
     */
    @GetMapping(value = "/chatMethod3")
    public String chatMethod3() {
        String role = "金融专家";
        String question = "股票如何选购";

        //1.构建提示词模版
        PromptTemplate promptTemplate = PromptTemplate.from("你是一个{{role}}助手，回答以下内容{{question}}");
        //2.由提示词模版生成提示词
        Prompt prompt = promptTemplate.apply(Map.of("role", role, "question", question));
        //3.提示词生成UserMessage
        UserMessage userMessage = prompt.toUserMessage();
        //4.调用大模型
        ChatResponse chatResponse = qwen.chat(userMessage);
        log.info("chatResponse: {}", chatResponse);
        return "success :" + DateUtil.now() + "<br> \n\n chatResponse: " + chatResponse.aiMessage().text();
    }
}
